package com.yunsom.testdemo.multiple_thread.concurrent_tools;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;

/**
 * @author Xbao
 * @description
 * @date 2022/5/10 16:38
 */
public class CallableAndFuture {

  public static class MyCallable implements Callable{

    private int flag = 0;

    public MyCallable(int flag){
      this.flag = flag;
    }

    @Override
    public Object call() throws Exception {

      if(this.flag == 0){
        return "flag = 0";
      }

      if(this.flag == 1){
        try {
          while (true){
            System.out.println("looping");
            Thread.sleep(1000);
          }
        } catch (InterruptedException e){
          System.out.println("interrupted exception occur");
        }
        return "false";
      } else {
        System.out.println("bad flag value!");
      }

      return null;
    }
  }

  public static void main(String[] args) {

    // 创建3个callable类型的任务
    MyCallable task1 = new MyCallable(0);
    MyCallable task2 = new MyCallable(1);
    MyCallable task3 = new MyCallable(2);

    // 创建一个执行任务的服务
    ExecutorService es = Executors.newFixedThreadPool(3);
    try{
      Future future1 = es.submit(task1);
      System.out.println("task1 result:" + future1.get());

      Future future2 = es.submit(task2);
      Thread.sleep(5000);
      System.out.println("task2 result:" + future2.cancel(true));

      Future future3 = es.submit(task3);
      System.out.println("task3 result:" + future3.get());
    } catch (Exception e){
      e.printStackTrace();
    }

    // 停止任务调度服务
    es.shutdownNow();

  }

}
